<template>
  <!---------- 查询表单form begin ----------->
  <a-form class="smart-query-form">
    <a-row class="smart-query-form-row">
      <a-form-item label="流程模型名称" class="smart-query-form-item">
        <a-input style="width: 200px" v-model:value="queryForm.name" placeholder="流程模型名称" />
      </a-form-item>
      <a-form-item class="smart-query-form-item">
        <a-button type="primary" @click="onSearch">
          <template #icon>
            <SearchOutlined />
          </template>
          查询
        </a-button>
        <a-button @click="resetQuery" class="smart-margin-left10">
          <template #icon>
            <ReloadOutlined />
          </template>
          重置
        </a-button>
      </a-form-item>
    </a-row>
  </a-form>

  <a-card size="small" :bordered="false" :hoverable="true">
    <!---------- 表格 begin ----------->
    <a-table
      size="small"
      :scroll="{ y: 800 }"
      :dataSource="tableData"
      :columns="columns"
      rowKey="id"
      bordered
      :loading="tableLoading"
      :pagination="false"
    >
      <template #bodyCell="{ record, column }">
        <template v-if="column.dataIndex === 'suupensionState'">
          <span>{{ record.suupensionState ? '已挂起' : '已激活' }}</span>
        </template>
        <template v-if="column.dataIndex === 'action'">
          <div class="smart-table-operate">
            <a-button @click="showXml(record)" type="link">查看xml文件</a-button>
            <a-button @click="getFlowDef(record)" type="link">发起流程</a-button>
            <a-button @click="showProcess(record)" type="link">查看流程信息</a-button>
          </div>
        </template>
      </template>
    </a-table>

    <div class="smart-query-table-page">
      <a-pagination
        showSizeChanger
        showQuickJumper
        show-less-items
        :pageSizeOptions="PAGE_SIZE_OPTIONS"
        :defaultPageSize="queryForm.pageSize"
        v-model:current="queryForm.pageNum"
        v-model:pageSize="queryForm.pageSize"
        :total="total"
        @change="queryData"
        @showSizeChange="queryData"
        :show-total="(total) => `共${total}条`"
      />
    </div>
  </a-card>

  <a-modal :open="visibleFlag" title="xml文件" :width="1200" @cancel="onClose">
    <div class="xml-pre-container" style="max-height: 600px; overflow-y: auto; white-space: pre-wrap">
      <pre>{{ xmlString }}</pre>
    </div>
  </a-modal>

  <!-- 发起流程模态框：显示 taskNodes 的 key 信息 -->
  <a-modal :open="visibleFlag2" title="发起流程" :width="800" @cancel="onClose2" :maskClosable="false" :confirmLoading="submitLoading" :footer="null">
    <!-- 加载状态 -->
    <template v-if="formLoading">
      <div class="text-center py-10">
        <a-spin size="large" />
        <p class="mt-4">加载流程配置中...</p>
      </div>
    </template>

    <!-- 动态表单：基于 taskNodes 渲染 -->
    <template v-else>
      <a-form ref="formRef" :model="dynamicValidateForm" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }" class="demo-dynamic">
        <!-- 循环 taskNodes 生成表单项，显示对应的 key 信息 -->
        <a-form-item
          v-for="(domain, index) in dynamicValidateForm.domains"
          :key="domain.compKey"
          :label="`${domain.name}（参数名：${domain.key}）`"
          :name="['domains', index, 'value']"
          :rules="[{ required: true, message: `请选择${domain.name}的${getTypeDesc(domain.type)}`, trigger: 'change' }]"
        >
          <!-- 负责人/候选用户：用户下拉（多选） -->
          <a-select
            v-if="domain.type === 'assignee' || domain.type === 'candidateUsers'"
            v-model:value="domain.value"
            mode="multiple"
            placeholder="请选择用户"
            style="width: 100%"
            :disabled="submitLoading"
          >
            <a-select-option v-for="user in users" :key="user.employeeId" :value="user.employeeId">
              {{ user.actualName }}（登录名：{{ user.loginName }} | ID：{{ user.employeeId }}）
            </a-select-option>
            <a-select-option v-if="users.length === 0" disabled>暂无用户数据</a-select-option>
          </a-select>

          <!-- 候选组：角色下拉（多选） -->
          <a-select
            v-else-if="domain.type === 'candidateGroups'"
            v-model:value="domain.value"
            mode="multiple"
            placeholder="请选择角色"
            style="width: 100%"
            :disabled="submitLoading"
          >
            <a-select-option v-for="role in roles" :key="role.roleId" :value="role.roleId">
              {{ role.roleName }}（ID：{{ role.roleId }}）
            </a-select-option>
            <a-select-option v-if="roles.length === 0" disabled>暂无角色数据</a-select-option>
          </a-select>
        </a-form-item>

        <!-- 表单操作 -->
        <a-form-item :wrapper-col="{ offset: 6, span: 16 }" class="form-actions">
          <a-button type="primary" @click="submitForm" :loading="submitLoading">提交</a-button>
          <a-button @click="resetForm" class="ml-4" :disabled="submitLoading">重置</a-button>
        </a-form-item>
      </a-form>
    </template>
  </a-modal>

  <a-modal :open="visibleFlag3" title="流程图" :width="800" @cancel="onClose3" :maskClosable="false" :confirmLoading="submitLoading">
    <!-- 直接绑定图片 -->
    <img :src="imageUrl" alt="流程图" style="max-width: 100%; max-height: 600px" />
  </a-modal>
</template>

<script setup>
  import { reactive, ref, onMounted } from 'vue';
  import { SearchOutlined, ReloadOutlined } from '@ant-design/icons-vue';
  import { PAGE_SIZE_OPTIONS } from '/@/constants/common-const';
  import { smartSentry } from '/@/lib/smart-sentry';
  import { flowDeployApi } from '/@/api/business/flowDeploy/flow-deploy-api.js';

  import { message } from 'ant-design-vue';

  // ---------------------------- 表格配置 ----------------------------
  const columns = ref([
    { title: '部署信息编号', dataIndex: 'id', ellipsis: true },
    { title: '流程模型key', dataIndex: 'flowKey', ellipsis: true },
    { title: '部署流程名称', dataIndex: 'name', ellipsis: true },
    { title: '分类', dataIndex: 'category', ellipsis: true },
    { title: '部署ID', dataIndex: 'deploymentId', ellipsis: true },
    // { title: '部署时间', dataIndex: 'deploymentTime', ellipsis: true },
    { title: '挂起状态', dataIndex: 'suupensionState', ellipsis: true },
    { title: '版本', dataIndex: 'version', ellipsis: true },
    { title: '操作', dataIndex: 'action', fixed: 'right', width: 180 },
  ]);

  // ---------------------------- 查询表单配置 ----------------------------
  const queryFormState = {
    name: undefined,
    pageNum: 1,
    pageSize: 10,
  };
  const queryForm = reactive({ ...queryFormState });
  const tableLoading = ref(false);
  const tableData = ref([]);
  const total = ref(0);

  // 重置查询
  function resetQuery() {
    const pageSize = queryForm.pageSize;
    Object.assign(queryForm, queryFormState);
    queryForm.pageSize = pageSize;
    queryData();
  }

  // 搜索
  function onSearch() {
    queryForm.pageNum = 1;
    queryData();
  }

  // 查询表格数据
  async function queryData() {
    tableLoading.value = true;
    try {
      const queryResult = await flowDeployApi.listProcDef(queryForm);
      tableData.value = queryResult.data?.list || [];
      total.value = queryResult.data?.total || 0;
    } catch (e) {
      smartSentry.captureError(e);
      message.error('查询流程列表失败，请稍后重试');
    } finally {
      tableLoading.value = false;
    }
  }

  // ---------------------------- 查看XML模态框 ----------------------------
  const visibleFlag = ref(false);
  const xmlString = ref('');

  async function showXml(record) {
    visibleFlag.value = true;
    try {
      const queryResult = await flowDeployApi.queryFlowXml(record.id);
      xmlString.value = queryResult.data || '无XML数据';
    } catch (e) {
      smartSentry.captureError(e);
      xmlString.value = '加载XML失败';
      message.error('加载XML文件失败，请稍后重试');
    }
  }

  function onClose() {
    visibleFlag.value = false;
    xmlString.value = '';
  }

  // ---------------------------- 发起流程模态框（核心：适配 taskNodes 结构） ----------------------------
  const visibleFlag2 = ref(false);
  const formRef = ref(null);
  const users = ref([]); // 后端返回的用户列表（含 employeeId/loginName）
  const roles = ref([]); // 后端返回的角色列表（含 roleId/roleName）
  const formLoading = ref(false);
  const submitLoading = ref(false);
  const currentDeploymentId = ref(''); // 当前流程部署ID
  const currentProcessId = ref('');
  // 动态表单数据模型：直接复用 taskNodes 的 key/name/type，新增 compKey 确保组件唯一
  const dynamicValidateForm = reactive({
    domains: [],
  });

  // 1. 打开发起流程模态框：加载 taskNodes 及用户/角色列表
  async function getFlowDef(record) {
    visibleFlag2.value = true;
    formLoading.value = true;
    // 关键修改：存储流程定义ID（record.id 即 act_re_procdef 表的 ID_）
    currentProcessId.value = record.id;
    // currentDeploymentId.value = record.deploymentId; // 原存储部署ID的代码，注释或删除
    dynamicValidateForm.domains = []; // 清空旧数据

    try {
      // 关键修改：若后端获取 taskNodes 仍需 deploymentId，可继续传 record.deploymentId（不影响）
      // 若后端已支持用 processId 获取，可改为传 currentProcessId.value，需与后端协商
      const queryResult = await flowDeployApi.getFlowDef(record.deploymentId);
      const responseData = queryResult.data || [];

      // 后续加载 taskNodes、用户/角色列表的逻辑保持不变...
      const taskNodes = responseData.filter((item) => item.key && item.name && item.type && !Array.isArray(item.role) && !Array.isArray(item.user));
      const roleItem = responseData.find((item) => Array.isArray(item.role));
      const userItem = responseData.find((item) => Array.isArray(item.user));
      roles.value = roleItem?.role || [];
      users.value = userItem?.user || [];

      dynamicValidateForm.domains = taskNodes.map((node, index) => ({
        compKey: `task_${index}_${node.name}_${Date.now()}`,
        key: node.key,
        name: node.name,
        type: node.type,
        value: [],
      }));

      console.log('加载的 taskNodes 表单配置：', dynamicValidateForm.domains);
      console.log('当前流程定义ID：', currentProcessId.value); // 新增调试日志，确认ID正确
    } catch (error) {
      smartSentry.captureError(error);
      dynamicValidateForm.domains = [];
      message.error('加载流程配置失败，请稍后重试');
    } finally {
      formLoading.value = false;
    }
  }

  // 2. 辅助函数：类型转中文描述（提升用户体验）
  function getTypeDesc(type) {
    const typeMap = {
      assignee: '负责人',
      candidateUsers: '候选用户',
      candidateGroups: '候选组',
    };
    return typeMap[type] || type;
  }

  // 3. 重置表单（清空选中状态）
  function resetForm() {
    if (formRef.value) {
      formRef.value.resetFields();
      // 重置所有表单项的选中值
      dynamicValidateForm.domains.forEach((domain) => {
        domain.value = [];
      });
    }
  }

  // 4. 关闭模态框（清空所有数据）
  function onClose2() {
    visibleFlag2.value = false;
    dynamicValidateForm.domains = [];
    users.value = [];
    roles.value = [];
    submitLoading.value = false;
  }

  // 5. 核心：提交流程（动态 key: 选中 ID 格式）
  // 5. 核心：提交流程（动态 key: 选中 ID 格式）
  async function submitForm() {
    // 步骤1：表单校验（保持不变）
    if (!formRef.value) return;
    try {
      await formRef.value.validate();
    } catch (error) {
      message.warning('请完成所有必填项的选择');
      return;
    }

    // 步骤2：组装提交参数（关键修改：传 processId 而非 deploymentId）
    const submitParams = new URLSearchParams();
    // 关键修改：传递流程定义ID（参数名改为 processId，需与后端一致）
    submitParams.append('processId', currentProcessId.value);
    // submitParams.append('deploymentId', currentDeploymentId.value); // 原传递部署ID的代码，注释或删除

    // 遍历表单项组装动态参数（保持不变）
    dynamicValidateForm.domains.forEach((domain) => {
      if (Array.isArray(domain.value) && domain.value.length > 0) {
        const paramKey = domain.key;
        const paramValue = domain.value.map((id) => parseInt(id, 10)).join(',');
        submitParams.append(paramKey, paramValue);
      }
    });

    // 打印最终提交参数（新增 processId 日志，确认参数正确）
    const finalParams = Object.fromEntries(submitParams.entries());
    console.log('最终提交给后端的参数：', finalParams);
    // 示例输出：{ processId: "Process_111:1:3d24308e-a3e7-11f0-84ef-be1ea488967b", user1: "2", user2: "44" }

    // 步骤3：发起后端请求（保持不变，确保后端接口接收 processId 参数）
    submitLoading.value = true;
    try {
      const response = await flowDeployApi.startProcess(submitParams);
      if (response.code === 0 || response.ok) {
        message.success('发起流程成功！');
        onClose2();
      } else {
        message.error(`发起流程失败：${response.msg || '未知错误'}`);
      }
    } catch (error) {
      smartSentry.captureError(error);
      message.error('发起流程请求异常，请稍后重试');
    } finally {
      submitLoading.value = false;
    }
  }

  // ---------------------------- 页面初始化 ----------------------------
  onMounted(() => {
    queryData();
  });

  //------------------查看流程图------------------
  const visibleFlag3 = ref(false);
  const imageUrl = ref('');

  async function showProcess(record) {
    visibleFlag3.value = true;
    const processDiagram = await flowDeployApi.getProcessDiagram(record.id);
    console.log(processDiagram);
    console.log(processDiagram.data);

    // 错误：const imageUrl = ... 会声明局部变量，覆盖外部响应式变量
    // 正确：直接给外部的imageUrl.value赋值
    imageUrl.value = `data:image/png;base64,${processDiagram.data}`;
    console.log(imageUrl.value); // 此时打印的才是正确的URL
  }

  function onClose3() {
    visibleFlag3.value = false;
  }
</script>

<style scoped>
  .xml-pre-container {
    font-family: 'Courier New', Courier, monospace;
    color: #333;
    padding: 16px;
    background: #f5f5f5;
    border-radius: 4px;
  }

  .form-actions {
    margin-top: 24px;
  }

  .smart-table-operate {
    display: flex;
    gap: 8px;
    align-items: center;
  }

  /* 优化表单项标签样式，避免参数名换行 */
  .ant-form-item-label > label {
    white-space: normal !important;
    line-height: 1.5;
    word-break: break-all;
  }
</style>
